package org.yxjme.ijkplayerlibrary.ijk.v;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import org.yxjme.ijkplayerlibrary.ijk.u.Settings;
import org.yxjme.ijkplayerlibrary.ijk.i.IJKVideoListener;

import java.io.IOException;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;


public class IJKVideoView  extends FrameLayout {

    private IMediaPlayer iMediaPlayer ;
    private SurfaceRenderView surfaceView ;
    private SurfaceHolder surfaceHolder ;
    private IJKVideoListener listener ;
    private Settings mSettings;


    public void setListener(IJKVideoListener listener) {
        this.listener = listener;
    }


    public IJKVideoView(@NonNull Context context) throws IOException {
        this(context,null);
    }


    public IJKVideoView(@NonNull Context context, @Nullable AttributeSet attrs) throws IOException {
        this(context, attrs,0);
    }


    public IJKVideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) throws IOException {
        super(context, attrs, defStyleAttr);
        initSurfaceView();
        mSettings = new Settings(context);
    }


    /**
     *
     */
    private void initSurfaceView(){
        surfaceView = new SurfaceRenderView(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER);
        surfaceView.setLayoutParams(layoutParams);
        this.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(callback);
    }



    private SurfaceHolder.Callback callback =  new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
        }
        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            load();
        }
        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        }
    };



    /**
     * 穿件播放器对象
     */
    private void createMediaPlayer() {
        synchronized (IJKVideoView.class){
            if (iMediaPlayer != null) {
                iMediaPlayer.stop();
                iMediaPlayer.setDisplay(null);
                iMediaPlayer.release();
            }


            IjkMediaPlayer ijkMediaPlayer = new IjkMediaPlayer();
            ijkMediaPlayerConfig(ijkMediaPlayer);
            iMediaPlayer = ijkMediaPlayer ;


            iMediaPlayer.setOnPreparedListener(preparedListener);
            iMediaPlayer.setOnInfoListener(infoListener);
            iMediaPlayer.setOnSeekCompleteListener(seekCompleteListener);
            iMediaPlayer.setOnBufferingUpdateListener(bufferingUpdateListener);
            iMediaPlayer.setOnErrorListener(errorListener);
            iMediaPlayer.setOnCompletionListener(completionListener);
            iMediaPlayer.setOnVideoSizeChangedListener(videoSizeChangedListener);
        }
    }


    private void ijkMediaPlayerConfig(IjkMediaPlayer ijkMediaPlayer) {
        //设置日志级别
        ijkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_DEBUG);
        //选择硬件解码器进行视频的解码
        if (mSettings.getUsingMediaCodec()) {
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
            if (mSettings.getUsingMediaCodecAutoRotate()) {
                ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
            } else {
                ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 0);
            }
            if (mSettings.getMediaCodecHandleResolutionChange()) {
                ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1);
            } else {
                ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 0);
            }
        } else {
            // 选择avcodec 进行软件解码
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 0);
        }
        if (mSettings.getUsingOpenSLES()) {
            //使用opensles 进行音频的解码播放
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 1);
        } else {
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 0);
        }

        String pixelFormat = mSettings.getPixelFormat();
        if (TextUtils.isEmpty(pixelFormat)) {
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", IjkMediaPlayer.SDL_FCC_RV32);
        } else {
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", pixelFormat);
        }
        //是否允许掉帧 1、允许 0、不允许
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1);
        //视频缓存
       // 好之后是否自动播放 1、允许 0、不允许
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", 0);

        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 1);//开启soundt
    }

    String videoUrl ="";
    //    String videoUrl="https://taojinapp.oss-cn-hangzhou.aliyuncs.com/ProductImage/2111/22/2111221426410151.mp4";
    public void load(){
        createMediaPlayer();
        try {
            iMediaPlayer.setDataSource(getContext(), Uri.parse(videoUrl));
//            iMediaPlayer.setDataSource(videoUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        iMediaPlayer.setDisplay(surfaceHolder);
        iMediaPlayer.prepareAsync();
    }


    public void setPath(String path) {
        if (TextUtils.equals("", videoUrl)) {
            videoUrl = path;
            initSurfaceView();
        } else {
            videoUrl = path;
            load();
        }
    }



    private IMediaPlayer.OnPreparedListener preparedListener = new IMediaPlayer.OnPreparedListener(){

        @Override
        public void onPrepared(IMediaPlayer iMediaPlayer) {
            DisplayMetrics dis = getContext().getResources().getDisplayMetrics();
            StringBuffer stringBuffer= new StringBuffer();
            int w = iMediaPlayer.getVideoWidth();
            int h = iMediaPlayer.getVideoHeight() ;
            stringBuffer.append("rootW = "+dis.widthPixels).append("\n");
            stringBuffer.append("rootH = "+dis.widthPixels).append("\n");
            stringBuffer.append("w = "+w).append("\n");
            stringBuffer.append("h = "+h).append("\n");
            surfaceView.setVideoSize(w,h);
            ViewGroup.LayoutParams param = getLayoutParams();
            param.height = h;
            param.width = w ;
            setLayoutParams(param);
            Log.v("[IJKVideoListener] - > ","onPrepared()"+stringBuffer.toString());
            if (listener!=null){
                listener.onPrepared();
            }
        }
    };


    private IMediaPlayer.OnCompletionListener completionListener = new IMediaPlayer.OnCompletionListener(){

        @Override
        public void onCompletion(IMediaPlayer iMediaPlayer) {
            if (listener!=null){
                listener.onCompletion();
            }
        }
    };


    private IMediaPlayer.OnInfoListener infoListener = new IMediaPlayer.OnInfoListener(){

        /**
         * int MEDIA_INFO_VIDEO_RENDERING_START = 3;//视频准备渲染
         * int MEDIA_INFO_BUFFERING_START = 701;//开始缓冲
         * int MEDIA_INFO_BUFFERING_END = 702;//缓冲结束
         * int MEDIA_INFO_VIDEO_ROTATION_CHANGED = 10001;//视频选择信息
         * int MEDIA_ERROR_SERVER_DIED = 100;//视频中断，一般是视频源异常或者不支持的视频类型。
         * int MEDIA_ERROR_IJK_PLAYER = -10000,//一般是视频源有问题或者数据格式不支持，比如音频不是AAC之类的
         * int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;//数据错误没有有效的回收
         *
         * @param iMediaPlayer
         * @param i
         * @param i1
         * @return
         */
        @Override
        public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
            if (listener!=null){
                listener.onInfo(i,i1);
            }
            return false;
        }
    };



    private IMediaPlayer.OnVideoSizeChangedListener videoSizeChangedListener = new IMediaPlayer.OnVideoSizeChangedListener(){

        @Override
        public void onVideoSizeChanged(IMediaPlayer iMediaPlayer, int i, int i1, int i2, int i3) {
            if (listener!=null){
                listener.onVideoSizeChanged(i,i1,i2,i3);
            }
        }
    };



    private IMediaPlayer.OnSeekCompleteListener seekCompleteListener = new IMediaPlayer.OnSeekCompleteListener(){

        @Override
        public void onSeekComplete(IMediaPlayer iMediaPlayer) {
            if (listener!=null){
                listener.onSeekComplete();
            }
        }
    };



    private IMediaPlayer.OnBufferingUpdateListener bufferingUpdateListener = new IMediaPlayer.OnBufferingUpdateListener(){

        @Override
        public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {
            if (listener!=null){
                listener.onBufferingUpdate(i);
            }
        }
    };



    private IMediaPlayer.OnErrorListener errorListener = new IMediaPlayer.OnErrorListener(){

        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
            if (listener!=null){
                listener.onError(i,i1);
            }
            return false;
        }
    };


    public void start() {
        if (iMediaPlayer != null&&!iMediaPlayer.isPlaying()) {
            iMediaPlayer.start();
        }
    }

    public void release() {
        if (iMediaPlayer != null) {
            iMediaPlayer.reset();
            iMediaPlayer.release();
            iMediaPlayer = null;
        }
    }



    public void pause() {
        if (iMediaPlayer != null) {
            iMediaPlayer.pause();
        }
    }



    public void stop() {
        if (iMediaPlayer != null) {
            iMediaPlayer.stop();
        }
    }



    public void reset() {
        if (iMediaPlayer != null) {
            iMediaPlayer.reset();
        }
    }


    public long getDuration() {
        if (iMediaPlayer != null) {
            return iMediaPlayer.getDuration();
        } else {
            return 0;
        }
    }




    public long getCurrentPosition() {
        if (iMediaPlayer != null) {
            return iMediaPlayer.getCurrentPosition();
        } else {
            return 0;
        }
    }




    public void seekTo(long l) {
        if (iMediaPlayer != null) {
            iMediaPlayer.seekTo(l);
        }
    }



}
